/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.cardarus.operatingsystem.struts.actions;

import com.cardarus.operatingsystem.domain.Item;
import com.cardarus.operatingsystem.model.BusinessModel;
import com.cardarus.operatingsystem.struts.forms.StockForm;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.struts.action.ActionErrors;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.action.ActionMessage;

/**
 * The action to add stock
 * @author bryan.hyde
 */
public class AddStockAction extends org.apache.struts.action.Action {

    /**
     *
     * @param mapping
     * @param form
     * @param request
     * @param response
     * @return
     * @throws Exception
     *
     * The class has a single function
     */
    @Override
    public ActionForward execute(ActionMapping mapping, ActionForm form,
            HttpServletRequest request, HttpServletResponse response)
            throws Exception {

        ActionErrors errors = new ActionErrors();
        StockForm sform = (StockForm) form;
        BusinessModel model = BusinessModel.getInstance();

        Item newStock = new Item(sform.getStockID(), sform.getStockName(), sform.getStockDescription(), sform.getStockPrice(), sform.getStockInventory());
        if (sform.getItemTypes().equalsIgnoreCase("card")) {
            newStock.setCard(true);
        } else if (sform.getItemTypes().equalsIgnoreCase("specialbox")) {
            newStock.setSpecialBox(true);
        } else {
            newStock.setSpecialBox(false);
            newStock.setCard(false);
        }

        if (!model.addNewStock(newStock)) {
            errors.add("StockID", new ActionMessage("error.addStock.failure"));
            addErrors(request, errors);
            return mapping.findForward("success");
        } else {
            return mapping.findForward("success");
        }
    }
}
